document.addEventListener('DOMContentLoaded', function () {
    const exchangeContainer = document.getElementById('exchange-list-container');
    const refreshStatusEl = document.getElementById('refresh-status');
    const defaultExchangeName = 'snackmq.default.direct';

    // 获取国际化文本的函数
    function getI18nText(key, defaultValue) {
        // 从页面中获取国际化文本，如果获取不到则使用默认值
        const element = document.querySelector(`[data-i18n="${key}"]`);
        return element ? element.textContent : defaultValue;
    }

    // 函数：根据数据动态构建 HTML
    const renderExchanges = (exchanges) => {
        exchangeContainer.innerHTML = '';
        if (!exchanges || exchanges.length === 0) {
            const noExchangesText = getI18nText('exchanges.no.exchanges', 'No custom exchanges found.');
            exchangeContainer.innerHTML = `<div class="text-center p-3">${noExchangesText}</div>`;
            return;
        }
        exchanges.forEach((exchange, index) => {
            const noBindingsText = getI18nText('exchanges.no.bindings', 'This exchange has no bindings.');
            let bindingsHtml = `<div class="text-muted">${noBindingsText}</div>`;
            if (exchange.bindings && exchange.bindings.length > 0) {
                const queueNameText = getI18nText('exchanges.queue.name', 'Queue Name');
                const routingKeyText = getI18nText('exchanges.routing.key', 'Routing Key');
                const actionsText = getI18nText('exchanges.actions', 'Actions');
                const unbindText = getI18nText('exchanges.unbind', 'Unbind');
                const confirmUnbindText = getI18nText('exchanges.confirm.unbind', 'Are you sure you want to remove this binding?');
                
                const bindingRows = exchange.bindings.map(binding => `
                    <tr>
                        <td>${binding.queueName}</td>
                        <td>${binding.routingKey}</td>
                        <td>
                            <form action="/exchanges/unbind" method="post" class="d-inline" onsubmit="return confirm('${confirmUnbindText}');">
                                <input type="hidden" name="exchangeName" value="${exchange.name}" />
                                <input type="hidden" name="queueName" value="${binding.queueName}" />
                                <input type="hidden" name="routingKey" value="${binding.routingKey}" />
                                <button type="submit" class="btn btn-warning btn-sm py-0 px-2">${unbindText}</button>
                            </form>
                        </td>
                    </tr>
                `).join('');
                bindingsHtml = `
                    <table class="table table-sm table-striped">
                        <thead><tr><th>${queueNameText}</th><th>${routingKeyText}</th><th>${actionsText}</th></tr></thead>
                        <tbody>${bindingRows}</tbody>
                    </table>
                `;
            }
            const deleteText = getI18nText('common.delete', 'Delete');
            const defaultText = getI18nText('exchanges.default', 'Default');
            const confirmDeleteText = getI18nText('exchanges.confirm.delete', 'Are you sure you want to delete this exchange and all its bindings? This cannot be undone.');
            
            const deleteButtonHtml = exchange.name !== defaultExchangeName ? `
                <div class="p-2">
                    <form action="/exchanges/delete" method="post" class="d-inline" onsubmit="return confirm('${confirmDeleteText}');">
                        <input type="hidden" name="exchangeName" value="${exchange.name}"/>
                        <button type="submit" class="btn btn-danger btn-sm">${deleteText}</button>
                    </form>
                </div>
            ` : `<div class="p-2"><span class="text-muted small fst-italic pe-2">${defaultText}</span></div>`;
            
            const bindingsText = getI18nText('exchanges.bindings', 'Bindings');
            const accordionItem = `
                <div class="accordion-item">
                    <h2 class="accordion-header d-flex align-items-center" id="heading${index}">
                        <button class="accordion-button collapsed flex-grow-1" type="button" data-bs-toggle="collapse"
                                data-bs-target="#collapse${index}" aria-expanded="false"
                                aria-controls="collapse${index}">
                            <strong>${exchange.name}</strong>&nbsp;
                            <span class="badge bg-info text-dark">${exchange.type}</span>
                        </button>
                        ${deleteButtonHtml}
                    </h2>
                    <div id="collapse${index}" class="accordion-collapse collapse"
                         aria-labelledby="heading${index}" data-bs-parent="#exchangesAccordion">
                        <div class="accordion-body">
                            <h6>${bindingsText}</h6>
                            ${bindingsHtml}
                        </div>
                    </div>
                </div>
            `;
            exchangeContainer.insertAdjacentHTML('beforeend', accordionItem);
        });
    };

    const updateExchanges = async () => {
        try {
            const response = await fetch('/api/exchanges');
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const exchanges = await response.json();
            renderExchanges(exchanges);
            const liveUpdateText = getI18nText('dashboard.live.update', 'Live Update');
            refreshStatusEl.innerHTML = `<span class="spinner-grow spinner-grow-sm text-success" role="status" aria-hidden="true"></span> ${liveUpdateText}`;
        } catch (error) {
            console.error('Failed to fetch exchanges data:', error);
            const updateFailedText = getI18nText('exchanges.update.failed', 'Update Failed');
            refreshStatusEl.innerHTML = `<span class="spinner-grow spinner-grow-sm text-danger" role="status" aria-hidden="true"></span> ${updateFailedText}`;
        }
    };

    setInterval(updateExchanges, 5000);
}); 